import 'package:async/async.dart';
import 'package:boss/color_constant.dart';
import 'package:boss/main.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:boss/ui/widget/calendar/util/date_util.dart';
import 'package:boss/ui/widget/calendar_bar.dart';
import 'package:boss/ui/widget/loader/loader_pull_refresh.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:flustars/flustars.dart' as flustars;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hi_common/hi_common.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class CollectionStatisticsIndex extends StatefulWidget {
  CollectionStatisticsIndex({Key key}) : super(key: key);

  @override
  CollectionStatisticsIndexState createState() => CollectionStatisticsIndexState();
}

class CollectionStatisticsIndexState extends State<CollectionStatisticsIndex> {
  final GlobalKey<LoaderPullRefreshState> loaderPullRefreshKey = GlobalKey<LoaderPullRefreshState>();
  DateTime startTime;

  DateTime endTime;

  RefreshController _refreshController;

  List<dynamic> dataList = [];

  int tipsNum = 0;

  @override
  void initState() {
    super.initState();
    _refreshController = RefreshController(initialRefresh: false);

    final now = DateTime.now();

    startTime = DateUtils.startOfTheDay(now);
    endTime = DateUtils.endOfTheDay(now);
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  refresh({bool needMove = true}) async {
    await _refreshController.requestRefresh(
      needMove: needMove,
      duration: Duration(milliseconds: 100),
    );
  }

  String dateTime2String(DateTime dateTime) {
    return flustars.DateUtil.formatDate(dateTime);
  }

  //发送邮箱
  sendMailbox(String e) async {
    showLoadingToast();
    try {
      var res = await api.sendEmailWithStatUserCashSumDataReport(
        startTime: dateTime2String(startTime),
        endTime: dateTime2String(endTime),
        email: e ?? '',
      );
      if (res.successful()) {
        toast("邮箱发送成功!");
        Navigator.pop(context);
      } else {
        toast(res.msg);
      }
    } catch (e) {} finally {
      hideLoadingToast();
    }
  }

  //格式化钱
  priceHandle(num) {
    return '¥' + AmountUtil.price2String((num) ?? 0);
  }

  List<TableRow> dataTableTableRow() {
    return (dataList ?? [])
        .map(
          (str) => TableRow(
              decoration: BoxDecoration(
                  border: Border(
                      bottom: BorderSide(
                width: 1.px,
                color: ColorConstant.e6e6,
              ))),
              children: [
//                TableDataCol("${str["payTime"] ?? '--'}", style: TextStyleConstant().normal_2_28),
                TableDataCol("${priceHandle(str["totalAmount"])}"),
                TableDataCol("${str["orderCount"] ?? '--'}"),
                TableDataCol("${priceHandle(str["inComeAmount"])}"),
                TableDataCol("${priceHandle(str["disCountAmount"])}"),
                TableDataCol("${str["customerCount"] ?? '--'}"),
                TableDataCol("${str["customerCount"] == 0 ? '--' : priceHandle(int.parse(((str["totalAmount"]) / str["customerCount"]).toStringAsFixed(0)))}"),
                TableDataCol("${str["orderCount"] == 0 ? '--' : priceHandle(int.parse(((str["totalAmount"]) / str["orderCount"]).toStringAsFixed(0)))}"),
                TableDataCol("${priceHandle(str["totalAmountX"])}"),
                TableDataCol("${str["orderCountX"] ?? '--'}"),
                TableDataCol("${priceHandle(str["inComeAmountX"])}"),
                TableDataCol("${priceHandle(str["disCountAmountX"])}"),
                TableDataCol("${str["customerCountX"] ?? '--'}"),
                TableDataCol(
                    "${str["customerCountX"] == 0 ? '--' : priceHandle(int.parse(((str["totalAmountX"]) / str["customerCountX"]).toStringAsFixed(0)))}"),
                TableDataCol("${str["orderCountX"] == 0 ? '--' : priceHandle(int.parse(((str["totalAmountX"]) / str["orderCountX"]).toStringAsFixed(0)))}"),
                TableDataCol("${priceHandle(str["totalAmountT"])}"),
                TableDataCol("${str["orderCountT"] ?? '--'}"),
                TableDataCol("${priceHandle(str["inComeAmountT"])}"),
                TableDataCol("${priceHandle(str["disCountAmountT"])}"),
                TableDataCol("${str["customerCountT"] ?? '--'}"),
                TableDataCol(
                    "${str["customerCountT"] == 0 ? '--' : priceHandle(int.parse(((str["totalAmountT"]) / str["customerCountT"]).toStringAsFixed(0)))}"),
                TableDataCol("${str["orderCountT"] == 0 ? '--' : priceHandle(int.parse(((str["totalAmountT"]) / str["orderCountT"]).toStringAsFixed(0)))}"),
                TableDataCol("${priceHandle(str["totalAmountA"])}"),
                TableDataCol("${str["orderCountA"] ?? '--'}"),
                TableDataCol("${priceHandle(str["inComeAmountA"])}"),
                TableDataCol("${priceHandle(str["disCountAmountA"])}"),
                TableDataCol("${str["customerCountA"] ?? '--'}"),
                TableDataCol(
                    "${str["customerCountA"] == 0 ? '--' : priceHandle(int.parse(((str["totalAmountA"]) / str["customerCountA"]).toStringAsFixed(0)))}"),
                TableDataCol("${str["orderCountA"] == 0 ? '--' : priceHandle(int.parse(((str["totalAmountA"]) / str["orderCountA"]).toStringAsFixed(0)))}",
                    rightBorder: false),
              ]),
        )
        .toList();
  }

  Widget TableDataCol(dynamic v, {bool rightBorder = true, TextStyle style}) {
    return v is Widget
        ? v
        : Container(
            decoration: rightBorder == true
                ? BoxDecoration(
                    border: Border(
                        right: BorderSide(
                    width: 1.px,
                    color: ColorConstant.e6e6,
                  )))
                : null,
            padding: EdgeInsets.symmetric(
              vertical: 22.w,
            ),
            child: Center(
              child: Text(
                "$v",
                style: style ?? TextStyleConstant().normal_1_28,
              ),
            ),
          );
  }

  //数据表格
  Widget TableCol(dynamic title) {
    return title is Widget
        ? title
        : Container(
            padding: EdgeInsets.symmetric(
              vertical: 22.w,
            ),
            child: Center(
              child: Text(
                "$title",
                style: TextStyleConstant().normal_2_28,
              ),
            ),
          );
  }

  Widget tableHeaderCol(
    String content1,
    String content2, {
    bool topRightBorder = false,
    bool bottomRightBorder = false,
  }) {
    return Container(
      height: 100.w,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Expanded(
            child: Container(
              width: double.infinity,
              decoration: BoxDecoration(
                  border: Border(
                right: topRightBorder == true
                    ? BorderSide(
                        width: 1.px,
                        color: ColorConstant.e6e6,
                      )
                    : BorderSide(
                        width: 0,
                        color: Colors.transparent,
                      ),
              )),
              child: Center(
                child: Text(
                  "$content1",
                  style: TextStyleConstant().normal_2_26,
                ),
              ),
            ),
          ),
          Expanded(
            child: Container(
              width: double.infinity,
              decoration: BoxDecoration(
                  border: Border(
                top: BorderSide(
                  width: 1.px,
                  color: ColorConstant.e6e6,
                ),
                right: bottomRightBorder == true
                    ? BorderSide(
                        width: 1.px,
                        color: ColorConstant.e6e6,
                      )
                    : BorderSide(
                        width: 0,
                        color: Colors.transparent,
                      ),
              )),
              child: Center(
                child: Text(
                  "$content2",
                  style: TextStyleConstant().normal_2_28,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget tableFixedColumn() {
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Table(columnWidths: {
            0: FixedColumnWidth(94.0)
          }, children: <TableRow>[
            TableRow(
                decoration: BoxDecoration(
                  color: Color.fromRGBO(245, 245, 245, 1),
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(14.w),
                  ),
                ),
                children: [
                  Container(
                    decoration: BoxDecoration(
                        border: Border(
                            right: BorderSide(
                      width: 1.px,
                      color: ColorConstant.e6e6,
                    ))),
                    height: 100.w,
                    child: Center(
                        child: Text(
                      "日期",
                      style: TextStyleConstant().normal_2_28,
                    )),
                  ),
                ]),
          ]),
          Table(
            columnWidths: {0: FixedColumnWidth(94.0)},
            children: (dataList ?? [])
                .map<TableRow>(
                  (str) => TableRow(
                    decoration: BoxDecoration(
                        border: Border(
                            bottom: BorderSide(
                      width: 1.px,
                      color: ColorConstant.e6e6,
                    ))),
                    children: [
                      TableDataCol("${str["payTime"] ?? '--'}", style: TextStyleConstant().normal_2_28),
                    ],
                  ),
                )
                .toList(),
          ),
        ],
      ),
    );
  }

  Widget dataTable() {
    return Container(
      margin: EdgeInsets.only(
//        top:28.w,
//        bottom:28.w,
//        left:26.w,
//        right:26.w,
          ),
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(
            14.w,
          ),
          boxShadow: [
            BoxShadow(
              color: ColorConstant.shadow,
              spreadRadius: 1.w,
              blurRadius: 9.w,
            )
          ],
        ),
        child: Container(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              tableFixedColumn(),
              Expanded(
                child: MScrollbar(
                  child: SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: Column(
                      children: <Widget>[
                        Table(columnWidths: {
                          //列宽
                          0: FixedColumnWidth(80.0),
                          1: FixedColumnWidth(80.0),
                          2: FixedColumnWidth(80.0),
                          3: FixedColumnWidth(80.0),
                          4: FixedColumnWidth(80.0),
                          5: FixedColumnWidth(80.0),
                          6: FixedColumnWidth(80.0),
                          7: FixedColumnWidth(80.0),
                          8: FixedColumnWidth(80.0),
                          9: FixedColumnWidth(80.0),
                          10: FixedColumnWidth(80.0),
                          11: FixedColumnWidth(80.0),
                          12: FixedColumnWidth(80.0),
                          13: FixedColumnWidth(80.0),
                          14: FixedColumnWidth(80.0),
                          15: FixedColumnWidth(80.0),
                          16: FixedColumnWidth(80.0),
                          17: FixedColumnWidth(80.0),
                          18: FixedColumnWidth(80.0),
                          19: FixedColumnWidth(80.0),
                          20: FixedColumnWidth(80.0),
                          21: FixedColumnWidth(80.0),
                          22: FixedColumnWidth(80.0),
                          23: FixedColumnWidth(80.0),
                          24: FixedColumnWidth(80.0),
                          25: FixedColumnWidth(80.0),
                          26: FixedColumnWidth(80.0),
                          27: FixedColumnWidth(80.0),
                        }, children: <TableRow>[
                          TableRow(
                              decoration: BoxDecoration(
                                color: Color.fromRGBO(245, 245, 245, 1),
                                borderRadius: BorderRadius.only(
                                  topRight: Radius.circular(14.w),
                                ),
                              ),
                              children: [
//                              Container(
//                                decoration: BoxDecoration(
//                                    border: Border(
//                                        right: BorderSide(
//                                          width: 1.px,
//                                          color: ColorConstant.e6e6,
//                                        ))),
//                                height: 100.w,
//                                child: Center(
//                                    child: Text(
//                                      "日期",
//                                      style: TextStyleConstant().normal_2_28,
//                                    )),
//                              ),
                                tableHeaderCol(
                                  "",
                                  "订单金额",
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "",
                                  "账单数",
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "",
                                  "实收金额",
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "合计",
                                  "优惠金额",
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "",
                                  "客流",
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "",
                                  "人均消费",
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "",
                                  "单均消费",
                                  topRightBorder: true,
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "",
                                  "订单金额",
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "",
                                  "账单数",
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "",
                                  "实收金额",
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "小程序外卖",
                                  "优惠金额",
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "",
                                  "客流",
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "",
                                  "人均消费",
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "",
                                  "单均消费",
                                  topRightBorder: true,
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "",
                                  "订单金额",
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "",
                                  "账单数",
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "",
                                  "实收金额",
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "堂食",
                                  "优惠金额",
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "",
                                  "客流",
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "",
                                  "人均消费",
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "",
                                  "单均消费",
                                  topRightBorder: true,
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "",
                                  "订单金额",
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "",
                                  "账单数",
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "",
                                  "实收金额",
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "服务员APP",
                                  "优惠金额",
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "",
                                  "客流",
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "",
                                  "人均消费",
                                  bottomRightBorder: true,
                                ),
                                tableHeaderCol(
                                  "",
                                  "单均消费",
                                ),
                              ]),
                          ...dataTableTableRow(),
                        ]),
                        SizedBox(
                          height: 12.w,
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<Result<List<dynamic>>> _loadTask() {
    Result.value([]);
  }

  Future<Result<List<dynamic>>> _refreshTask() async {
    var res = await api.statSalesChannelData(
      startTime: dateTime2String(startTime),
      endTime: dateTime2String(endTime),
    );
    if (res.successful()) {
      dataList = (res.data["sumVo"] ?? []);
      tipsNum = (res.data["inComeAmount"] ?? 0);
      setState(() {});
      return Result.value([1]);
    } else {
      toast(res.msg);
      return Result.value([]);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(top: 16.w),
      child: Container(
        padding: EdgeInsets.symmetric(
          horizontal: 28.w,
        ),
        child: Column(
          children: <Widget>[
            CalendarBar(
              startDateTime: startTime,
              endDateTime: endTime,
              onDateTimeChanged: (List<DateTime> dateTime) {
                startTime = dateTime[0];
                endTime = dateTime[1];
                loaderPullRefreshKey.currentState.refresh();
              },
              type: CalendarType.ymdhm,
            ),
            Expanded(
              child: LoaderPullRefresh<dynamic>(
                  key: loaderPullRefreshKey,
                  loadTask: _loadTask,
                  refreshTask: _refreshTask,
                  builder: (context) {
                    return SingleChildScrollView(
                      child: Column(
                        children: <Widget>[
                          Padding(
                            padding: EdgeInsets.only(
                              top: 12.w,
                              bottom: 12.w,
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: <Widget>[
                                Text(
                                  "门店渠道",
                                  style: TextStyleConstant().normal_1_36,
                                ),
                                Text(
                                  " 未包含小费金额 ${priceHandle(tipsNum)}",
                                  style: TextStyleConstant().normal_3_28,
                                ),
                              ],
                            ),
                          ),
                          dataTable(),
                          SizedBox(
                            height: 20.w,
                          ),
                        ],
                      ),
                    );
                  }),
            ),
          ],
        ),
      ),
    );
  }
}
